package com.mouse.magent.web.util;

import com.mouse.magent.web.entity.common.JwtInfo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

@Log4j2
@Component
public class JwtUtil {
    public static String SECRET = "qazwsx123444$#%#()*&& asdaswwi1235 ?;!@#kmmmpom in***xx**&";

    @Value("${custom.jwt.password:qazwsx123444$#%#()*&& asdaswwi1235 ?;!@#kmmmpom in***xx**&}")
    private String password;
    public final static String TOKEN_START = "Bearer ";

    @PostConstruct
    public void init() {
        this.SECRET = this.password;
    }

    public static String generateToken(JwtInfo jwtInfo) {
        Map<String, Object> map = CollectionUtil.objectToMap(jwtInfo);
        return Jwts.builder().setClaims(map)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();

    }

    public static JwtInfo validateToken(String token) {
        JwtInfo jwtInfo = null;
        try {
            token = token.replace(TOKEN_START, "");
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            if (body.get("jti") == null) {
                return null;
            }
            jwtInfo = CollectionUtil.mapToObject(body, JwtInfo.class);
        } catch (Exception e) {
        }
        return jwtInfo;

    }

}
